package com.sie.jta308demo.a108dev;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.bankcomm.peripheral.BankCardInfoBean;
import com.bankcomm.peripheral.EmvOptions;
import com.bankcomm.peripheral.IdentityInfoBean;
import com.bankcomm.peripheral.PeripheralCallback;
import com.sie.framework.device.SiecomDevice;
import com.sie.framework.device.SiecomTask;
import com.sie.framework.listen.DeviceConStatusListen;
import com.sie.framework.module.KeyBroadModule;
import com.sie.jta308demo.R;
import com.sie.peripheral.SiecomPeripheral;
import com.sie.tools.ByteTool;
import com.sie.tools.LogUtil;
import com.sie.tools.StringUtil;
import com.sie.zhq.tool.ToastUtils;

import org.json.JSONException;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

//import bankcomm.io.base.impl.siecom.ApduActionImpl;

/**
 * 为交通银行定制的demo
 * 
 * @author zhq
 * 
 */
@SuppressLint("SimpleDateFormat")
public class MainActivity extends Activity implements View.OnClickListener {

	SiecomPeripheral periphera = null;

	private Button ICCardNo, ICcardField, MsrCardNo, IDcardBtn, NFCCardNo,
			NFCLabel, MkeyInput, WkeyInput, StartInput, mBtnfingerCode, CardNO,
			ReadPSAM, StartInput2;

	private TextView mainKeyStr, workKeyStr, fingerInfo, btlist_title;

	private EditText ICCardNoStr, IcinterfaceStr, MsrCardNoStr, IDcardInfo,
			CardNOStr, NFCCardLabelStr, CardNoStr, editText1, PSAMStr,
			editText2, NFCCardNoStr;
	private ImageView photo;
	private NoScrollListView bondListView = null;
	private BtListAdapter _bondAdapter = null;
	private ArrayList<HashMap<String, String>> bondData;
	public String device_name = "";
	private Context context;
	private boolean flag = false;
//	public PrinterInstance printer;
	private String TAG = "MainActivity";
	private Switch mSwitchCipherType,mSwitchTimes;
	public int mCipherType = 1; // 1 国际  2 国密
	public int mInputTimes = 1;
	// 主密钥
	static byte[] master_key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
			0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };

	// 工作密钥
	static byte[] work_key = { 0x12, 0x34, 0x56, 0x78, (byte) 0x90,
			(byte) 0xab, (byte) 0xcd, (byte) 0xef, 0x01, 0x02, 0x03, 0x04,
			0x05, 0x06, 0x07, 0x08 };

	final String bankCardNo = "6230710101010708018";// 卡号

	final static int MSG_CONNED = 0;
	final static int MSG_CONNING = 1;
	final static int MSG_NOCONN = 2;
	final static int MSG_CANT = 3;
	final static int APDU_RESULT = 4;
	public ProgressDialog m_pDialog;

	// 任务超时
	int timeOut = 10 * 1000;// 60秒


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 异常记录
		// CrashHandler crashHandler = CrashHandler.getInstance();
		// crashHandler.init(this);
		// 初始化界面元素
		initUI();
		ProgressDialogInit();
		context = this;
		// 初始化外设
		periphera = new SiecomPeripheral();
		if (periphera instanceof SiecomPeripheral) {
			periphera.speakerId = R.raw.qingluru;
			periphera.setContext(this);

		}
		// 线连。要选择uart方式
		registerBoradcastReceiver();
		// 开始连接
		initConnect();
//		registerReceiver(mReceiver, makeFilter());
		connectPrinter();
	}

	public void connectPrinter() {
//		periphera.connectPrinter(new PeripheralCallback() {
//
//			@Override
//			public void onSuccess(Bundle arg0) {
//				// TODO Auto-generated method stub
//				int status = periphera.getPrinterStatus(null);
//				LogUtil.mLog("打印机 已经连接成功 status:" + status);
//				// try {
//				// Print();
//				// } catch (JSONException e) {
//				// // TODO Auto-generated catch block
//				// e.printStackTrace();
//				// }
//			}
//
//			@Override
//			public void onFail(Bundle bundle) {
//				// TODO Auto-generated method stub
//				int status = periphera.getPrinterStatus(null);
//				LogUtil.mLog("status:" + status);
//				LogUtil.mLog(bundle.getString("code") + "--"
//						+ bundle.getString("message"));
//			}
//		});
	}

	public void initLineConnect() {

	}

	public void Print() throws JSONException {

		String data = "{\"string\":[{\"content\":\"交通银行上海市分行\r\n日期:2016-9-23\r\n时间:11:40:48\r\n业务种类：  客户服务-签约-对私购物车\r\n业务编码：\r\n业务类型:\r\n客户信息:\r\n证件种类：0102\t第二代居民身份证\r\n证件号码：110104194206087055\r\n客户号：0115644053269288\r\n户名：漠北\r\n签约账号：6222620110023846075\r\n签约服务:\r\n产品约:\r\n\r\n期权宝\r\n业务种类：开通\r\n开通\r\n\r\n\"}]}";

		// JSONObject data = new JSONObject();
		//
		// JSONArray bmparr = new JSONArray();
		//
		// JSONObject bmpObj = new JSONObject();
		// bmpObj.put("path","/sdcard/wltlib/zp.bmp");
		// bmpObj.put("alignment","right");
		//
		//
		// bmparr.put(bmpObj);
		//
		// data.put("bitmap", bmparr);
		// JSONArray strarr = new JSONArray();
		//
		// JSONObject strObj = new JSONObject();
		// strObj.put("content","测试摄啊啊啊啊htc\r\n我擦");
		// strObj.put("alignment","left");
		// strObj.put("bold",true);
		// strObj.put("underline",true);
		// strObj.put("rowSpan","10");
		// strObj.put("columnSpan","10");
		// strObj.put("tab","2");
		// strObj.put("angle","90");
		// strarr.put(strObj);
		// data.put("string", strarr);
		//
		// JSONArray bararr = new JSONArray();
		//
		// JSONObject barObj = new JSONObject();
		// barObj.put("content","1234567");
		// bararr.put(barObj);
		// data.put("barCode", bararr);
		//
		// JSONArray QRbararr = new JSONArray();
		//
		// JSONObject QRobj = new JSONObject();
		// barObj.put("content","http://www.baidu.com");
		// QRbararr.put(QRobj);
		// data.put("2DbarCode", bararr);
		//
		// Log.e("test","print:"+data.toString());
		//
		// Log.e("test","print:"+data.toString());
		//

//		periphera.printDataString(data.toString(), new PeripheralCallback() {
//
//			@Override
//			public void onSuccess(Bundle bundle) {
//				// TODO Auto-generated method stub
//
//				String data2 = "{\"bitmap\":[{\"path\":\"\\/storage/emulated/0/wltlib/zp.bmp\",\"alignment\":\"left\"}]}";
//				periphera.printDataString(data2, new PeripheralCallback() {
//
//					@Override
//					public void onFail(Bundle bundle) {
//						LogUtil.mLog(bundle.getString("code") + "--"
//								+ bundle.getString("message"));
//
//					}
//
//					@Override
//					public void onSuccess(Bundle arg0) {
//						// TODO Auto-generated method stub
//
//					}
//
//				});
//
//			}
//
//			@Override
//			public void onFail(Bundle bundle) {
//				// TODO Auto-generated method stub
//				LogUtil.mLog(bundle.getString("code") + "--"
//						+ bundle.getString("message"));
//			}
//		});

	}

	private void registerBoradcastReceiver() {
		//注册监听
        IntentFilter stateChangeFilter = new IntentFilter();
        stateChangeFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        stateChangeFilter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        stateChangeFilter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        stateChangeFilter.addAction("android.bluetooth.a2dp.profile.action.CONNECTION_STATE_CHANGED");
        stateChangeFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_OFF");
        stateChangeFilter.addAction("android.bluetooth.BluetoothAdapter.STATE_ON");

        registerReceiver(stateChangeReceiver, stateChangeFilter);
    }

    private BroadcastReceiver stateChangeReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //Log.e("GJ", "收到"+action);
            if (action.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) {

            } else if (action.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) {
                //蓝牙连接被切断
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String name = device.getName();
                //Log.e("GJ", "已经断开");
                return;
            }
        }
    };


	/**
	 * 连接蓝牙
	 *
	 * @param
	 * @param
	 */
	private void initConnect() {
		final long start = System.currentTimeMillis();
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub

				int ret = periphera.connectDevice(2);
				long end = System.currentTimeMillis();
				if(ret == 0){
					Message msg = new Message();
					msg.what = MSG_CONNED;
					msg.obj = (end - start);
					handler.sendMessage(msg);
					flag = true;
					LogUtil.e("connected", "success");
				}
				LogUtil.e("connect:", ret + "----");

				LogUtil.e(TAG, ret + "----连接耗时:" + (end - start));
				periphera.getSerialNo(new PeripheralCallback() {
					@Override
					public void onSuccess(Bundle bundle) {
						LogUtil.e(TAG,"getSerialNo ==" + bundle.getString("data"));
					}

					@Override
					public void onFail(Bundle bundle) {

					}
				},10*1000);
				// periphera.setContext(context);
				// periphera.connectDevice(1);

			}
		}).start();

		/**
		 * 建议使用这个方法作为监听整个连接状态
		 */
		periphera.listenDeviceStatus(new PeripheralCallback() {

			@Override
			public void onSuccess(Bundle bundle) {
				// TODO Auto-generated method stub
				/**
				 * 这里通知连接成功
				 */
				Message msg = new Message();
				msg.what = MSG_CONNED;
				handler.sendMessage(msg);
				flag = true;
				Log.e("connected", "success");

			}

			@Override
			public void onFail(Bundle bundle) {
				// TODO Auto-generated method stub
				Log.e("connected", "fail");
				LogUtil.mLog(bundle.getString("code") + "--"
						+ bundle.getString("message"));
			}
		});
        /**
         * 用于监听整个通讯过程中蓝牙连接变化
         */
        SiecomDevice.deviceConnStatusChange(new DeviceConStatusListen() {

            @Override
            public void onDisconnect() {
                Log.e("conn", "onDisconnect");
                /**
                 * 断开之后可以取消任务了 ，参数isConnected，因为断开所以已经false
                 */
                SiecomDevice.cancelLastTask(false);
                handler.sendEmptyMessage(MSG_NOCONN);

            }

            @Override
            public void connected() {
				Message msg = new Message();
				msg.what = MSG_CONNED;
				handler.sendMessage(msg);
				flag = true;

                LogUtil.e(TAG, "deviceConnStatusChange connected");
            }

            @Override
            public void connecting() {
				Message msg = new Message();
				msg.what = MSG_CONNING;
				handler.sendMessage(msg);
				flag = true;
                Log.e("MainActivity", "connecting");
            }
        });


	}



	private void initUI() {

		setTitle("蓝牙未连接");
		ICCardNo = (Button) findViewById(R.id.ICCardNo);
		ICCardNo.setOnClickListener(this);
		ICCardNoStr = (EditText) findViewById(R.id.ICCardNoStr);
		ICcardField = (Button) findViewById(R.id.Icinterface);
		ICcardField.setOnClickListener(this);
		IcinterfaceStr = (EditText) findViewById(R.id.IcinterfaceStr);
		MsrCardNo = (Button) findViewById(R.id.MsrCardNo);
		MsrCardNo.setOnClickListener(this);
		MsrCardNoStr = (EditText) findViewById(R.id.MsrCardNoStr);

		IDcardBtn = (Button) findViewById(R.id.IDcardBtn);
		IDcardBtn.setOnClickListener(this);
		IDcardInfo = (EditText) findViewById(R.id.IDcardInfo);
		photo = (ImageView) findViewById(R.id.IDcardPhoto);

		NFCCardNo = (Button) findViewById(R.id.NFCCardNo);
		NFCCardNo.setOnClickListener(this);
		NFCCardNoStr = (EditText) findViewById(R.id.NFCCardNoStr);
		NFCLabel = (Button) findViewById(R.id.NFCLabel); //读取标签
		NFCLabel.setOnClickListener(this);
		NFCLabel.setVisibility(View.INVISIBLE);

		NFCCardLabelStr = (EditText) findViewById(R.id.NFCCardLabelStr);

		mainKeyStr = (TextView) findViewById(R.id.mainKeyStr);
		mainKeyStr.setText(StringUtil.bytesToHexString(master_key,
				master_key.length));
		mainKeyStr.setTextSize(15);
		MkeyInput = (Button) findViewById(R.id.MkeyInput);
		MkeyInput.setOnClickListener(this);

		workKeyStr = (TextView) findViewById(R.id.workKeyStr);
		workKeyStr.setText(StringUtil.bytesToHexString(work_key,
				work_key.length));
		workKeyStr.setTextSize(15);
		WkeyInput = (Button) findViewById(R.id.WkeyInput);
		WkeyInput.setOnClickListener(this);

		CardNoStr = (EditText) findViewById(R.id.CardNoStr);
		CardNoStr.setText(bankCardNo);
		StartInput = (Button) findViewById(R.id.StartInput);
		StartInput.setOnClickListener(this);
		editText1 = (EditText) findViewById(R.id.editText1);

		mBtnfingerCode = (Button) findViewById(R.id.fingerCode);
		mBtnfingerCode.setOnClickListener(this);
		fingerInfo = (TextView) findViewById(R.id.fingerInfo);
		btlist_title = (TextView) findViewById(R.id.btlist_title);

		CardNO = (Button) findViewById(R.id.WRITE_NO);
		CardNO.setOnClickListener(this);

		CardNOStr = (EditText) findViewById(R.id.cardNoStr);
//		CardNOStr.setVisibility(View.INVISIBLE);
		CardNoStr.setVisibility(View.INVISIBLE);
		ReadPSAM = (Button) findViewById(R.id.ReadPSAM);
		ReadPSAM.setOnClickListener(this);
		PSAMStr = (EditText) findViewById(R.id.PSAMStr);

		StartInput2 = (Button) findViewById(R.id.StartInput2);
		StartInput2.setOnClickListener(this);
		StartInput2.setVisibility(View.INVISIBLE);

		editText2 = (EditText) findViewById(R.id.editText2);
//		editText2.setText("https://qr.test.com/009033011408152000010138884344282846198");

		mSwitchCipherType = (Switch) findViewById(R.id.switch_3des_or_sm4);
		mSwitchCipherType.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
					buttonView.setText("国密SM4");
					Toast.makeText(MainActivity.this,"已切换为国密",Toast.LENGTH_SHORT).show();
					mCipherType = 2;
				}else {
                	mCipherType = 1;
					buttonView.setText("国际3DES");
					Toast.makeText(MainActivity.this,"已切换为国际",Toast.LENGTH_SHORT).show();
				}
            }
        });

		mSwitchTimes = (Switch) findViewById(R.id.switch_input_times);
		mSwitchTimes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					mInputTimes = 2;
					buttonView.setText("输入2次");
				}else {
					mInputTimes = 1;
					buttonView.setText("输入1次");
				}
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		// if (!flag) {
		//
		// Toast.makeText(this, "蓝牙尚未连接", Toast.LENGTH_SHORT).show();
		// return;
		//
		// }

		switch (v.getId()) {
		case R.id.ICCardNo:
			ICCardNo.setEnabled(false);

			// 读取IC卡槽
			ReadCard(SiecomPeripheral.IC_TYPE);
//			readIcTags();
			break;
		case R.id.MsrCardNo:
			// 读取磁条卡卡号和三磁道数据
			ReadCard(SiecomPeripheral.MSR_TYPE);
			break;
		case R.id.NFCCardNo:
			NFCCardNo.setEnabled(false);
			// 读取非接IC卡
			ReadCard(SiecomPeripheral.PICC_TYPE);
			break;
		case R.id.Icinterface:
			// 自动类型
			ReadCard(SiecomPeripheral.AUTO_TYPE);
			break;

		case R.id.IDcardBtn:
			// 读取身份证
			readIDInfo();

			break;

		case R.id.NFCLabel:
			// 读取标签，这里以ARQC做例子
			readIcTags();
			// validateARPC();
			break;

		case R.id.WRITE_NO:
//			getSerialNo();//获取序列号
			// 写入编号
			getPublicKey517();
//			periphera.loadMainKeyCN(new PeripheralCallback() {
//
//				@Override
//				public void onSuccess(Bundle pubKey) {
//					// TODO Auto-generated method stub
//					String dsdsds = pubKey.getString("data");
//					Log.e("GJ","最终结果+" +dsdsds);
//
//				}
//
//				@Override
//				public void onFail(Bundle bundle) {
//					// TODO Auto-generated method stub
//					//Log.e("GJ", bundle.getInt("code") + "--");
//					DbgLogger.mLog(bundle.getString("code") + "--"
//							+ bundle.getString("message"));
//				}
//			}, ByteTool.hexStr2Bytes("3731383532333233A8FA14879879C1DCA147DA0C5FC96C17DAE2BA32F7E7A1610DEB5FE8DB8C006E994182805687B063791A1C82664E199F65DF2B9C6143C403CEFF461D82DEFC17EC2CA734A0412929441BC1C20CD4999CCB936E696DDF644F203B1C23B67D0F2A2A4447A33F3D387C43C5F722028C6745"),
//					ByteTool.hexStr2Bytes("54DDD243E67833BD5402D70ED7549495B34B0A92DFBA42D32CD80AF3D2435CD576D4F112FA0191B5AD5C82572DE345CA5A1602B65553024EFC093803A12F7AAE"),
//					ByteTool.hexStr2Bytes("87C7EAD4E35C1C770EC7186680BC85929C0911EEEC1E5938591494DA0CFB54EC3D8EFF68E1FCCB135316BDC65C0412CD5FE22FC7E1C2161D16D00755FFF52C8A"),
//					ByteTool.hexStr2Bytes("159D071B436E9289B189B040C8F7750B68CF223C894200CAD03002F0570A4663D0810B68D692ED901E002328C48A195B3BD87538B1EE36F3ED0B5817DEEA7E65"),
//					01,2,600000);

			break;
		case R.id.MkeyInput:
			// 灌入主密钥
//			inputMkey();
			 inputMkey517();
//			loadMainKeyCN();

			break;
		case R.id.WkeyInput:

			// 灌入工作密钥
			inputWkey517();

			break;
		case R.id.StartInput:
			// 启动密码键盘输入，第一次使用先灌入主和工作密钥
			StartInput();

			//测试读取NFC标签内容
//			testReadNFCTag();
			break;

		case R.id.fingerCode:

			fingerCode();

			// 获取指纹特征码
			toastfuc("请按指纹");
			break;

		case R.id.ReadPSAM:
			String times = PSAMStr.getText().toString();
			if(!TextUtils.isEmpty(times)){
				try {
					mReadTimes = Integer.parseInt(times);
					if(mReadTimes > 0){
						mSuccessTimes = 0;
						mFailTimes = 0;
						toastfuc("设置" + mReadTimes + "次 成功");
						return;
					}
				}catch (Exception e){
					e.printStackTrace();
				}

			}

			periphera.getInitInfo(new PeripheralCallback() {

				@Override
				public void onSuccess(Bundle bundle) {
					// TODO Auto-generated method stub
					String data = bundle.getString("data");
					Log.e("GJ", "getInitInfo----------"+data);
				}

				@Override
				public void onFail(Bundle bundle) {
					// TODO Auto-generated method stub
					Log.e("GJ", "getInitInfo fail == " + bundle.getString("message"));
				}
			}, 2, 60000);

			break;

		case R.id.StartInput2:
			// SiecomDevice.beep();
			//
			// /**
			// * 这是读取唯一芯片号，这是我们这边的方法
			// */
//			 periphera.getKeyStatus(new PeripheralCallback() {
//
//			 @Override
//			 public void onSuccess(Bundle arg0) {
//			 // TODO Auto-generated method stub
//
//			 //Log.e("GJ",arg0.getString("data"));
//			 }
//
//			 @Override
//			 public void onFail(Bundle bundle) {
//			 // TODO Auto-generated method stub
//			 DbgLogger.mLog(bundle.getString("code")+"--"+bundle.getString("message"));
//			 }
//			 },"", 3000);
//			periphera.cancelOperation();

//			periphera.readICTradeDetail(PeripheralInterface.READMODE_IC_NONCONTACT,new PeripheralCallback() {
//
//				@Override
//				public void onSuccess(Bundle bundle) {
//					// TODO Auto-generated method stub
//					ToastUtils.showToast(context, "输入完成"+bundle.getString("data"));
//					Log.e("readICTradeDetail",bundle.getString("data"));
//
//				}
//
//				@Override
//				public void onFail(Bundle arg0) {
//					// TODO Auto-generated method stub
//
//				}
//			}, 60000);

//			periphera.getVersion();
//			periphera.cancelOperation();

//			testApdu(); //
//			testWriteNFCTag(); //测试标签数据

			break;
		}
	}

	//2020.11.10 交行新业务 使用apdu指令
//	private void testApdu(){
//	    Runnable runnable = new Runnable() {
//            @Override
//            public void run() {
//                ApduActionImpl apduAction = new ApduActionImpl();
//                boolean suc = apduAction.connect();
//                Log.e(TAG,"连接成功：" + suc);
//                String inData = "00A404000E315041592E5359532E4444463031FF";
//                inData = "00A4040005F044434559";
//                inData = "80058000FF0980FBE3514AC462B99C886578C79724308201BD30820161A0030201020210202010130167887BC5A54E133ECD76B3300C06082A811CCF550183750500303C310B300906035504061302434E31123010060355040A0C09505342435F746573743119301706035504030C10505342435F444345505F746573744341301E170D3230313031333033313932335A170D3233313031333033313932335A303D310B300906035504061302434E31123010060355040A0C09505342435F74657374311A301806035504030C1120303038333030303030303036303238353059301306072A8648CE3D020106082A811CCF5501822D03420004ACDBDB980AE8DB65F77900";
//                inData = "8022000000";
//
//                byte receive[] = apduAction.transceive(ByteTool.hexStr2Bytes(inData));
//                if(receive != null){
//                    String str = ByteTool.byte2hex(receive);
//                    Log.e(TAG,"outData = " + str );
//                    Message message = new Message();
//                    message.what = APDU_RESULT;
//                    message.obj = str;
//                    handler.sendMessage(message);
//                }
//                apduAction.disconnect();
//            }
//        };
//        SingletonThreadPool.getInstance().submit(runnable);
//	}



//	private void testWriteNFCTag(){
//		String str = editText2.getText().toString();
//		JSONObject jsonObject = new JSONObject();
//		try {
//			if(TextUtils.isEmpty(str)){
//				return;
//			}
//			jsonObject.put("NFCstring",str);
//
//
//		} catch (JSONException e) {
//			e.printStackTrace();
//		}
//		ApduActionImpl apduAction = new ApduActionImpl();
//		String data = jsonObject.toString();
//		Log.e(TAG,"JSONStr ==" + data);
//		int timeOut = 11*1000;
//		apduAction.writeNFCdata(data, new PeripheralCallback() {
//			@Override
//			public void onSuccess(Bundle bundle) {
//				Log.e(TAG,"onSuccess " + bundle.getString("message"));
//				Toast.makeText(MainActivity.this,"数据写入成功了",Toast.LENGTH_SHORT).show();
//
//			}
//
//			@Override
//			public void onFail(Bundle bundle) {
//				final int code = bundle.getInt("code");
//				final String msg = bundle.getString("message");
//				Log.e(TAG,"onFail code =" + code + "-- msg ==" + msg);
//				Toast.makeText(MainActivity.this,"code = " + code +  " --- msg == " + msg,Toast.LENGTH_SHORT).show();
//
//			}
//		},timeOut);
//
//	}
//
//	private void testReadNFCTag(){
//		editText2.setText("");
//		ApduActionImpl apduAction = new ApduActionImpl();
//		 apduAction.readNFCdata(new PeripheralCallback() {
//			@Override
//			public void onSuccess(Bundle bundle) {
//				final String outData = ByteTool.byte2hex(bundle.getByteArray("message"));
//				Log.e(TAG," read onSuccess = " + outData);
//
//				editText2.setText(outData);
//			}
//
//			@Override
//			public void onFail(final Bundle bundle) {
//				final int code = bundle.getInt("code");
//				final String msg = bundle.getString("message");
//				Log.e(TAG," read onFail" + code + "--- message =" +bundle.getString("message"));
//				Toast.makeText(MainActivity.this,"code = " + code + " message ==" + msg,Toast.LENGTH_SHORT).show();
//
//			}
//		},10*1000);
//
//
//	}

	public void disConnectPrinter(){
		// 断开 连接打印机
//			DbgLogger.mLog("打印机状态：" + periphera.getPrinterStatus(null));
		// 断开打印机 15811220417 sprt 秦工
		// if(periphera.getPrinterStatus(null) == 1){
		// connectPrinter();
		// }
		// if(periphera.getPrinterStatus(null) == 0){
		// BluetoothOperation op = new BluetoothOperation(null);
		// if(op != null){
		// op.openPrinter();
		// }
		// }
	}

	private void loadMainKeyCN(){
		periphera.getInitInfo(new PeripheralCallback() {

			@Override
			public void onSuccess(Bundle bundle) {
				// TODO Auto-generated method stub
				periphera.loadMainKeyCN(new PeripheralCallback() {

							@Override
							public void onSuccess(Bundle pubKey) {
								// TODO Auto-generated method stub
								String dsdsds = pubKey.getString("data");
								Log.e("GJ","最终结果+" +dsdsds);

							}

							@Override
							public void onFail(Bundle bundle) {
								// TODO Auto-generated method stub
								//Log.e("GJ", bundle.getInt("code") + "--");
								LogUtil.mLog(bundle.getString("code") + "--"
										+ bundle.getString("message"));
							}
						}, ByteTool.hexStr2Bytes("37313835323332339A52B0B37A00FA321FDBDD561032822226DC8AADBBE4CE241965BF5A9B01DE8C90D6A19CE985CDF7BA0740CC17446AA0AE695E7F29850775C215F4DCC50E097C8E9C874F3C43C5922D5156E9A9A6B15D6205326E45140035B4741A852C5EE8EF60A27F47C6B4B2D533BE989819DFEC5C"),
						ByteTool.hexStr2Bytes("5BCAAE8776B1848481FFE62D4D55070B5BF4FA7784002F40C359436E804D71D1DEAC0B4D740FF968FC0D5E8F8C46E97BFE4F641273CD6BEA9F304F56BF84A717"),
						ByteTool.hexStr2Bytes("D8274D369D926BF86AEF35FD410EAEC04E75F0CA681494EAAE011209716978E489439222255722553B758C1203969B61D8FFC23ABF7A643E5268AE935062EBE0"),
						ByteTool.hexStr2Bytes("A4866C5ABD2C2E2A89565ADF6312D16AB5CFCFCF1197F51292E5B186304D3C944A445D2AFC80E2C7CAB0891AC138830FD2AD0FFD6FF708C98F0762A391C5198C"),
						01,2,600000);

			}

			@Override
			public void onFail(Bundle bundle) {
				// TODO Auto-generated method stub
//					//Log.e("GJ", bundle.getString("message"));
			}
		}, 2, 60000);
	}

	//获取国际或国密的密钥对
	private void getPublicKey517(){
		/**
		 * 加密类型 11  国际       12 国密
		 * timeOut  超时
		 */
		int cipherType = mCipherType;  //11  国际 RSA      12 国密 SM2
		periphera.getPublicKey(new PeripheralCallback() {

			@Override
			public void onSuccess(Bundle bundle) {
//				byte[] pubKey = bundle.getByteArray("data");
				String pubKey = bundle.getString("data");
				ToastUtils.showToast(context, "生成密钥对"+pubKey);
				Log.e("GJ", "公钥:"+pubKey);
				LogUtil.mLog("pubKey==" +pubKey);
			}

			@Override
			public void onFail(Bundle bundle) {
				String message = bundle.getString("message");
				ToastUtils.showToast(context, "生成密钥对失败"+message);
				LogUtil.mLog("error message==" +message);
			}
		}, cipherType, 20);
	}
//  3DES 测试数据
//	1.分量1 与分量2 异或得到主密钥并注入
//    KEY1 : 1234567890ABCDEF 1111 1111 1111 1111
//    KEY2 : 2222 2222 2222 2222 ABCDEF1234567890
//		异或结果：3016745AB289EFCDBADCFE0325476981
//
//2.更新主密钥
//    密钥从服务器得到
//    check码：569EC1E6AF5D3038
//    密钥：D506E2176376E463AD5726EB3E3B1C57
//（解密后明文为 20CED9B602586DC2FE58D31FB0FD7F8C）
//3.工作密钥
//    check码：FAB7660908D5EE83
//    工作密钥：914B174F70B1EFDCE50046B99C18B77F
//（明文为 6E76B36486587615C73149F4708C34F8）
//4.卡号 622439830000013757 和密码 123456
//异或得到 0612AC66FFFFEC8A
//    加密得到密文 00C069DBA9628897 上传服务器解密

	private void inputMkey517(){
		/*
		 * 主密钥内容
		 * 主密钥号  交通银行为1
		 * 加密类型
		 * 超时
		 */
		IDcardInfo.setText("D4C393C74F24BD7C302EDF7148F7C14E8738D61BA94CCE861CA2CE3E1FF291199EEB6CCAC385F88E2A0761A790D247DBA4DD5A330FE3FFA63F44699C1411A14E0A9EDC670FA0CF46DAD216154B552F0FB6F41E3F4BE93DC50F562205F44A0A01FF152F49B61BE194CB285175ADD433811F4E546D58CF198F3C28D62F3C29A9591F973E1D703A2A8C719593045742041C99A3C22A453D2C41C3F806E0F9F2DCE5EDD04B9D924F71F3208692FAD44C155B05AA131EC5101814DE68E0B04353E1D6D7C270CF6AE8D2E0F0B3BF5911FF3489D61192B28C4E4CEA17E1CF04B8FFFAFE9E51FFB05289A676E502C2E45A1C7EFF8289994BC2C60458B727CB94A8FDF7CC");
		String mainKeyStr = IDcardInfo.getText().toString();
		if(mainKeyStr.length()<32){
			ToastUtils.showToast(context, "请先设置密钥");
			return;
		}
		byte[] mainKeyByte = ByteTool.str2Bcd(mainKeyStr);
		int mainKeyCode = 1;  //密钥索引 为1
		int cipherTpye = mCipherType;  //加密类型  1 国际 3des  2 国密 SM2
		periphera.loadMainKey(new PeripheralCallback() {

			@Override
			public void onSuccess(Bundle bundle) {
//				byte[] checkValue = bundle.getByteArray("data");
				String checkValue = bundle.getString("data");
				LogUtil.mLog("checkValue==" +checkValue);
//				Log.e("GJ", "公钥:"+ByteTool.byte2hex(pubKey));
				Log.e("GJ", "校验码:"+checkValue);
				ToastUtils.showToast(context, "主密钥下载成功"+checkValue);
			}

			@Override
			public void onFail(Bundle bundle) {
				String message = bundle.getString("message");
				LogUtil.mLog("error message==" +message);
				ToastUtils.showToast(context, "主密钥下载失败"+message);
			}
		}, mainKeyByte, mainKeyCode, cipherTpye, 10);
	}

	private void inputWkey517(){
		int mainKeyCode = 1;
		int workKeyCode = 1;
		int cipherType = mCipherType; //1 3des 国际          2 SM4 国密
		work_key = ByteTool.hexStr2Bytes("22222222222222222222222222222222");
		periphera.loadWorkKey(new PeripheralCallback() {

			@Override
			public void onSuccess(Bundle bundle) {
//				byte[] checkValue = bundle.getByteArray("data");
				String checkValue = bundle.getString("data");
				ToastUtils.showToast(context, "工作密钥下载成功"+checkValue);
				Log.e("GJ", "工作秘钥校验码:"+checkValue);
				LogUtil.mLog("checkValue==" +checkValue);
			}

			@Override
			public void onFail(Bundle bundle) {
				String message = bundle.getString("message");
				LogUtil.mLog("error message==" +message);
				ToastUtils.showToast(context, "工作密钥下载失败"+message);
			}
		}, work_key, mainKeyCode, workKeyCode, cipherType, 10);
	}

	private void StartInput() {
		CardNoStr.setText("622439830000013757");
		String cardno = CardNoStr.getText().toString();
		int cipherType = mCipherType; //加密类型 1国际   2 国密
		int inputTimes = mInputTimes;
		if (cardno.length() == 0) {
			Toast.makeText(this, "银行卡号不能为空", Toast.LENGTH_SHORT).show();
			return;
		}
		editText1.setText("");
		periphera.getPin(inputTimes, cardno, new PeripheralCallback() {

			@Override
			public void onSuccess(Bundle bundle) {
				// TODO Auto-generated method stub

				int op = bundle.getInt("option");

				switch (op) {
				case KeyBroadModule.OP_CANCEL:
					// editText1.setText("");
					// Toast.makeText(context, "已经取消输入", Toast.LENGTH_SHORT)
					// .show();
					ToastUtils.showToast(context, "取消输入");
					Log.e("onfail", "quxiaoshurule........");
					break;
				case KeyBroadModule.OP_FINISH:
//					final byte[] pin = bundle.getByteArray("password");
					final String pin = bundle.getString("data");
//					Log.e("OP_FINISH", ByteTool.byte2hex(pin));
					Log.e(TAG,"pinblock=" + bundle.getString("data"));
					ToastUtils.showToast(context, "完成输入"+bundle.getString("data"));
					// x9.8加密的话，转换一下才是人眼可读的String
					runOnUiThread(new Runnable() {
						@Override
						public void run() {
							 editText1.setText(pin);
						}
					});


					break;

				case KeyBroadModule.OP_INPUTTING:
					// 显示*号的个数
					int num = bundle.getInt("keyNum");
					Log.e(TAG,"mSecretText==" + bundle.getString("data"));
					StringBuffer buf = new StringBuffer();
					for (int i = 0; i < num; i++)
						buf.append("*");

					// editText1.setText(buf.toString());
					break;
				default:
					break;
				}
			}

			@Override
			public void onFail(Bundle bundle) {
				// TODO Auto-generated method stub
//				Toast.makeText(context, "GGG"+bundle.getString("message"), Toast.LENGTH_LONG).show();
				Log.e(TAG, bundle.getString("code") + "\n"+bundle.getString("message"));
				LogUtil.mLog(bundle.getString("code") + "--"
						+ bundle.getString("message"));

				//Log.e("GJ", "成功超时");
			}
		}, cipherType, timeOut);

	}

	private void readIcTags() {
		// NFCCardLabelStr.setText("");
		/**
		 * 这里只是说明下做交易时可能会用到的设置项目，到时候可以拆一下这个设置项
		 */
		EmvOptions options = new EmvOptions();
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");// 设置日期格式
		String time = df.format(new Date());
		options.setTime(time);

		byte[] MerchCateCode = new byte[2];
		MerchCateCode[0] = 0x00;
		MerchCateCode[1] = 0x01;
		options.setMerchCateCode(MerchCateCode);
		String MerchId = "123456789012345";
		options.setMerchId(MerchId.getBytes());
		options.setMerchName("EMV LIBRARY".getBytes());
		options.setTermId("12345678".getBytes());
		options.setTerminalType((byte) 0x22);
		options.setSupportPSESel((byte) 0x01);
		byte[] Capability = { (byte) 0xE0, (byte) 0x60, (byte) 0xC8 };
		options.setCapability(Capability);
		byte[] ExCapability = { (byte) 0x60, (byte) 0x00, (byte) 0xF0,
				(byte) 0x20, (byte) 0x01 };
		options.setExCapability(ExCapability);
		byte[] CountryCode = { (byte) 0x01, (byte) 0x56 };
		options.setCountryCode(CountryCode);
		options.setTransCurrCode(CountryCode);
		options.setTransCurrExp((byte) 0x02);
		options.setReferCurrCode(CountryCode);
		options.setCL_TransLimit(100000);
		options.setTransType((byte) 0x00);
		options.setECTSI((byte) 0x01);
		options.setEC_TermLimit(10000);
		options.setEC_bTermLimitCheck((byte) 0x01);
		byte[] TermTransQuali = { 0x24, 0x00, 0x00, (byte) 0x80 };
		options.setTermTransQuali(TermTransQuali);
		options.setCL_bStatusCheck((byte) 0x00);
		options.setCL_CVMLimit(10000);
		options.setCL_FloorLimit(20000);
		options.setTransNo(1);

		// 这里是55域的标签，要取卡号必须有5A和57标签
		String[] tags = { "5A", "57", "9F26", "9F27", "9F10", "9F37", "9F36",
				"95", "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33",
				"9F34" };
		options.setTags(tags);

		// 这里使用自动
		periphera.ReadIcCardTags(SiecomPeripheral.AUTO_TYPE, options,
				new PeripheralCallback() {

					@Override
					public void onSuccess(Bundle bundle) {
						// TODO Auto-generated method stub
						String TLV = bundle.getString("data");// 返回的数据

						BankCardInfoBean infobean = bundle
								.getParcelable("BankCardInfoBean");
						Log.e("info:", infobean.toString());
						Log.e("TLV", TLV);

						final int cardType = bundle.getInt("cardType");// 卡类型

						/**
						 * 考虑到网络传输这个数据多数情况下是String，需要来回转换的问题，
						 * 还有validateARPC这个方法很可能是在回调中使用，采用多层回调比较难看
						 *
						 */
						String arpc = "910A222A0C26DE7B9AEF3030";//
						// 91开头，脚本是72开头
						String script = "72199F1804D7C4E3C1861004DA9F790A0000000001005A90B2E100";
						script = "";
						validateARPC();  //检验脚本
//						periphera.validateARPC(cardType, arpc, script, 0,
////								new PeripheralCallback() {
////
////									@Override
////									public void onSuccess(Bundle bud) {
////										// TODO Auto-generated method stub
////										Log.e("data",
////												bud.getString("data"));
////									}
////
////									@Override
////									public void onFail(Bundle bundle) {
////										// TODO Auto-generated method stub
////
////										DbgLogger.mLog(bundle.getString("code")
////												+ "--"
////												+ bundle.getString("message"));
////									}
////
////								}, 30);

					}

					@Override
					public void onFail(Bundle bundle) {
						// TODO Auto-generated method stub

//						Toast.makeText(context, "GGG"+bundle.getString("message"), Toast.LENGTH_LONG).show();
						LogUtil.mLog(bundle.getString("code") + "--"
								+ bundle.getString("message"));
					}
				}, timeOut);

	}

	private void validateARPC() {
		String content = "910A2501EEC5A3FDBF563030";
		String script = "860F04DA9F790A000000000000A4B17D6D860F04DA9F770A0000001000008C09E6BF862D04DC010C2870229F61123433313232313139383830373136313231589F6201105F2006C5CBB0D8D3EEA168BB5A";
		script = "7251860F04DA9F790A000000000000A4B17D6D860F04DA9F770A0000001000008C09E6BF862D04DC010C2870229F61123433313232313139383830373136313231589F6201105F2006C5CBB0D8D3EEA168BB5A";
		int autoFlag = 0;
		int type = 1;
		periphera.validateARPC(type, content, script, autoFlag,
				new PeripheralCallback() {

					@Override
					public void onSuccess(Bundle bundle) {
						// TODO Auto-generated method stub
						LogUtil.mLog(bundle.getString("data"));
					}

					@Override
					public void onFail(Bundle bundle) {
						// TODO Auto-generated method stub
						LogUtil.mLog(bundle.getString("code")
								+ bundle.getString("message"));
					}
				}, 10);
	}

	private int mSuccessTimes = 0;
	private int mFailTimes = 0;
	private static int  mReadTimes;
	/**
	 * 读取身份证
	 */
	private void readIDInfo() {
//		IDcardInfo.setText("");
		final long now = System.currentTimeMillis();
		photo.setImageResource(R.drawable.photo);
		// m_pDialog.show();

//		periphera.connectDevice(PeripheralInterface.STATUS_DEVICE_CONNECTED_2);
		
		periphera.ReadIDCardInfo(null,new PeripheralCallback() {

			@Override
			public void onSuccess(Bundle bundle) {
				mSuccessTimes ++ ;
				// TODO Auto-generated method stub
				final IdentityInfoBean bean = bundle.getParcelable("data");
				//Log.e("GJ", "姓名"+bean.fullName);
				ToastUtils.showToast(context, bean.gAddress + "" +bean.photoLocal);
				// Bitmap front = IDPicture.readFromSD("template/front.bmp");
				// Bitmap back = IDPicture.readFromSD("template/back.bmp");
				// IDPicture.createPic(front, back, bean, "outpic");
//				Log.e("beanType",bean.fCardTag + "--图片大小：" + bean.photo.getByteCount());
				final long time = (System.currentTimeMillis() - now);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						photo.setImageBitmap(bean.photo);
						IDcardInfo.setText(" usetime:" + time + "\r" + bean.toString() );
						ToastUtils.showToast(context,bean.toString());
						NFCCardLabelStr.setText("成功" + mSuccessTimes + "----" + "失败" + mFailTimes);

						LogUtil.e(TAG,  "useTime:" + time+ "ms" + "成功" + mSuccessTimes + "----" + "失败" + mFailTimes);

						if(mSuccessTimes < mReadTimes){
							try {
								Thread.sleep(100);
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
							readIDInfo();
						}
					}
				});


				
			}

			@Override
			public void onFail(Bundle bundle) {
				mFailTimes ++;
				// TODO Auto-generated method stub
//				Toast.makeText(context, "GGG"+bundle.getString("message"), Toast.LENGTH_LONG).show();
				LogUtil.e(TAG,"readIDInfo onFail :" + bundle.getString("code") + "--" + bundle.getString("message"));

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						NFCCardLabelStr.setText("成功" + mSuccessTimes + "----" + "失败" + mFailTimes);
						LogUtil.e(TAG,   "成功" + mSuccessTimes + "----" + "失败" + mFailTimes);
//						if(mSuccessTimes < mReadTimes){
//							try {
//								Thread.sleep(100);
//							} catch (InterruptedException e) {
//								e.printStackTrace();
//							}
//							readIDInfo();
//						}
					}
				});


//                periphera.getSerialNo(new PeripheralCallback() {
//
//                    @Override
//                    public void onSuccess(Bundle bundle) {
//                        // TODO Auto-generated method stub
//
//                        //Log.e("GJ", new String(bundle.getByteArray("data")));
//                    }
//
//                    @Override
//                    public void onFail(Bundle bundle) {
//                        // TODO Auto-generated method stub
////					Toast.makeText(context, "GGG"+bundle.getString("message"), Toast.LENGTH_LONG).show();
//                        Log.e("ddd", bundle.getInt("code") + "--");
//                        LogUtil.mLog(bundle.getString("code") + "--"
//                                + bundle.getString("message"));
//                    }
//                }, 30 * 1000);

			}
		}, timeOut);

	}

	/**
	 * 读取卡片信息
	 * 
	 * @param readMode
	 */

	private void ReadCard(final int readMode) {
		// m_pDialog.show())
		MsrCardNoStr.setText("");
		NFCCardNoStr.setText("");
		IDcardInfo.setText("");
		ICCardNoStr.setText("");
		photo.setImageBitmap(null);
		final long now = System.currentTimeMillis();
		LogUtil.e("readMode", "read mode ==" + readMode);
		periphera.ReadBankCardInfo(readMode, new PeripheralCallback() {

			@Override
			public void onSuccess(Bundle bundle) {

				// TODO Auto-generated method stub
				/**
				 * 从bundle里取出数据 这里的数据，似乎不同的银行都不太重视，我手上也就建行的数据全一点，其他的行有很多都是随意充填的。
				 * 最好先判断一下null和长度
				 * 
				 */
				final BankCardInfoBean infobean = bundle.getParcelable("data");
				//Log.e("GJ", "55:"+bundle.getString("55field"));
				final long useTime = System.currentTimeMillis() - now;
				Log.e("GJ", "info:"+infobean.toString() + "\n useTime:" + useTime);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if(readMode == 2){
							ICCardNoStr.setText("用时:" + useTime + "-" + infobean.cardNo);
						}
						if(readMode == 1){
							MsrCardNoStr.setText("用时:" + useTime + "-" + infobean.cardNo);
						}
						if(readMode == 3){
							NFCCardNoStr.setText("用时:" + useTime + "-" + infobean.cardNo);
						}
						IDcardInfo.setText("useTime:" + useTime + "\n" +infobean.toString());
						ICCardNo.setEnabled(true);
						NFCCardNo.setEnabled(true);
					}
				});

//				readIcTags();

			}

			@Override
			public void onFail(Bundle bundle) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						ICCardNo.setEnabled(true);
						NFCCardNo.setEnabled(true);
					}
				});

				// TODO Auto-generated method stub
//				Toast.makeText(context, "GGG"+bundle.getString("message"), Toast.LENGTH_LONG).show();
				LogUtil.mLog(bundle.get("code") + "--"
						+ bundle.getString("message"));
			}
		}, timeOut);

	}
    public void getSerialNo(){
	    periphera.getSerialNo(new PeripheralCallback() {
            @Override
            public void onSuccess(Bundle bundle) {
                byte[] sn = bundle.getByteArray("data");
                Log.e(TAG,"sn == " + new String(sn));
            }

            @Override
            public void onFail(Bundle bundle) {

            }
        },2000);
    }

	private void fingerCode() {
		// m_pDialog.show();
		mBtnfingerCode.setEnabled(false);
		final long start = System.currentTimeMillis();
		fingerInfo.setText("");
		periphera.getFingerCode(new PeripheralCallback() {

			@Override
			public void onSuccess(Bundle bundle) {

				// TODO Auto-generated method stub
				final String fingerCode = bundle.getString("dataStr");
				byte[] byteFinger = bundle.getByteArray("data");
//				 fingerInfo.setText("特征码：" +
//				 String tcMutToGb = SiecomFingerToBank.toBankTC(fingerCode);
				final long end = System.currentTimeMillis();
				Log.e(TAG, "fingerCodeStr == " + fingerCode + " \n useTime : " +(end - start) );
//				Log.e(TAG, "fingerCodeByte == "+ByteTool.bytearrayToHexString(byteFinger, byteFinger.length));
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						fingerInfo.setText(fingerCode + " \n useTime : " +(end - start) );
						mBtnfingerCode.setEnabled(true);
					}
				});


				// m_pDialog.hide();
			}

			@Override
			public void onFail(Bundle bundle) {
				// TODO Auto-generated method stub
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mBtnfingerCode.setEnabled(false);
					}
				});

				Log.e("fingerCode", "onfail");


				LogUtil.e(TAG,bundle.getString("code") + "--"
						+ bundle.getString("message"));

			}
		}, timeOut);

	}

	/**
	 * 灌工作密钥
	 */
	private void inputWkey() {
		/**
		 * 这里还是用我们自己灌注密钥方法
		 */
		int keyindex = 0;// 使用第0组存储密钥；
		int mainKeyIndex = 0;// 对应的主密钥索引，参考之前注入的主密钥使用第0组
		SiecomTask.TaskCallback taskCallback = new SiecomTask.TaskCallback() {
			@Override
			public void onStart(Bundle bundle) {

				toastfuc("开始注入工作密钥");
			}

			@Override
			public void onSucceed(Bundle bundle) {

				LogUtil.mLog(bundle.toString());
			}

			@Override
			public void onError(Bundle bundle) {
				int code = bundle.getInt("code");
				String msg = bundle.getString("message");

				LogUtil.mLog(bundle.getString("code") + "--"
						+ bundle.getString("message"));
			}
		};
		SiecomDevice.inputWorkKey(keyindex, mainKeyIndex, work_key,
				taskCallback);

	}

	/**
	 * 灌主密钥
	 */
	private void inputMkey() {

		/**
		 * 这里还是用我们的主密钥灌注方法
		 * 
		 * 如果需要主密钥是String，需要转换成16进制的byte，请使用ByteTool.hexStringToBytes(hexString)
		 * ;转换成byte
		 */
		int keyindex = 0;// 使用第0组存储密钥；
		if(mCipherType == 1){
			keyindex = 0;
		}else {
			keyindex = 10;
		}

		SiecomTask.TaskCallback taskCallback = new SiecomTask.TaskCallback() {
			@Override
			public void onStart(Bundle bundle) {

				toastfuc("开始注入主密钥");
			}

			@Override
			public void onSucceed(Bundle bundle) {
				LogUtil.mLog(bundle.getString("code") + "--"
						+ bundle.getString("message")
						+ ByteTool.byte2hex(bundle.getByteArray("data"))
				);
				toastfuc("注入主密钥成功");
			}

			@Override
			public void onError(Bundle bundle) {
				int code = bundle.getInt("code");
				String msg = bundle.getString("message");

				LogUtil.mLog(code + "," + msg);
				LogUtil.mLog(bundle.getString("code") + "--"
						+ bundle.getString("message"));
			}
		};

		SiecomDevice.inputMainKey(keyindex, master_key, taskCallback);
	}

	
	
	/**
	 * 蓝牙状态接收的handler
	 */
	private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_CONNED: {
                    setTitle("蓝牙已连接");
                    if(null != msg.obj){
                        toastfuc("蓝牙已连接 用时:" + msg.obj );
                    }
                    btlist_title.setText("设备" + device_name + "蓝牙已连接");

                    break;
                }
                case MSG_CONNING: {
                    setTitle("蓝牙连接中");
                    toastfuc("蓝牙连接中");
                    break;
                }
                case MSG_NOCONN: {
                    setTitle("蓝牙断开中");
                    toastfuc("蓝牙断开中");
                    break;

                }
                case MSG_CANT: {
                    setTitle("蓝牙无法连接");
                    toastfuc("蓝牙无法连接");
                    break;
                }

                case APDU_RESULT:
                    String result = (String) msg.obj;
                    editText2.setText(result);
                    break;

            }
            return false;
        }
    });

	private void toastfuc(final String msg) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
			}
		});

	}

	@Override
	protected void onDestroy() {
		// TODO 自动生成的方法存根
//		periphera.disconnBtnClick();
		super.onDestroy();
		unregisterReceiver(stateChangeReceiver);
		long start = System.currentTimeMillis();
		periphera.disConnectDevice();
		long end = System.currentTimeMillis();
		Log.e(TAG,"disConnectDevice use time " + (end -start));
	}
	private void ProgressDialogInit() {

		m_pDialog = new ProgressDialog(this);

		// 设置进度条风格，风格为圆形，旋转的
		m_pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

		// 设置ProgressDialog 提示信息
		m_pDialog.setMessage("请稍等……");

		// 设置ProgressDialog 的进度条是否不明确
		m_pDialog.setIndeterminate(false);

		// 设置ProgressDialog 是否可以按退回按键取消
		m_pDialog.setCancelable(false);
		m_pDialog.setButton(DialogInterface.BUTTON_POSITIVE, "取消操作",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						// 強制取消操作,實驗性
						SiecomDevice.cancelLastTask(true);
					}
				});
	}



}
